package com.dolphin.servicemap.remot;

import com.dolphin.common.constant.AmapConfigConstants;
import com.dolphin.common.dto.ResponseResult;
import com.dolphin.common.request.PointDTO;
import com.dolphin.common.request.PointRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URLEncoder;

@Service
@Slf4j
public class PointClient {

    @Value("${amap.key}")
    private String amapKey;
    @Value("${amap.sid}")
    private String amapSid;

    @Autowired
    RestTemplate restTemplate;

    public ResponseResult upload(PointRequest pointRequest) {

        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.POINT_UPLOAD_URL);
        url.append("?key=" + amapKey);
        url.append("&");
        url.append("sid=" + amapSid);
        url.append("&");
        url.append("tid=" + pointRequest.getTid());
        url.append("&");
        url.append("trid=" + pointRequest.getTrid());
        url.append("&");

        ObjectMapper objectMapper = new ObjectMapper();
        String pointString = "";
        try {
            pointString = objectMapper.writeValueAsString(pointRequest.getPoints());
            url.append("points="+ URLEncoder.encode(pointString, "UTF-8"));
        } catch (Exception e) {
            log.error(e.getMessage());
        }


        log.info("高德地图请求参数："+pointString.toString());

        log.info("高德地图请求："+url.toString());
        ResponseEntity<String> response = restTemplate.postForEntity(URI.create(url.toString()), null, String.class);
        log.info("高德地图响应："+response.getBody().toString());


        return ResponseResult.success();
    }
}
